package com.research;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import ocr.client.Client;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Bitmap.Config;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

public class RecognitionAc extends Activity implements OnClickListener,
		OnTouchListener {
	static int CAPTURE_PICTURE_CODE = 1;
	final static int RECOGNITION_OK = 1;
	final static int RECOGNITION_ERROR = 2;
	final static int CONNECTION_ERROR = 3;

	LinearLayout layout;

	ImageView picture_view;
	TextView recog_text;
	Spinner spinner;

	Button capture_button;
	Button translate_button;

	Button ocr_button;

	Bitmap origin_picture;// origin picture

	Bitmap recog_picture;// repair picture

	String character;
	String language;

	float start_x;
	float start_y;

	float end_x;
	float end_y;

	int scale_start_x;
	int scale_start_y;
	int scale_end_x;
	int scale_end_y;

	ProgressDialog dialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reconigtion);

		// get view widget
		picture_view = (ImageView) findViewById(R.id.picture);
		recog_text = (TextView) findViewById(R.id.character);
		capture_button = (Button) findViewById(R.id.capture);
		translate_button = (Button) findViewById(R.id.translate);
		ocr_button = (Button) findViewById(R.id.ocr);
		spinner = (Spinner) findViewById(R.id.language);

		layout = (LinearLayout) findViewById(R.id.picture_view_layout);
		// set action

		capture_button.setOnClickListener(this);
		translate_button.setOnClickListener(this);
		ocr_button.setOnClickListener(this);

		picture_view.setOnTouchListener(this);
		layout.setOnTouchListener(this);

		// get picture
		origin_picture = BitmapFactory.decodeResource(getResources(),
				R.drawable.vietnamese);
		recog_picture = BitmapFactory.decodeResource(getResources(),
				R.drawable.vietnamese);

		// spinner language
		spinnerLanguage();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.menu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case R.id.Capture:
			doCapture();
			break;
		case R.id.Translate:
			doTranslate();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {

			// get taked picture
			Bundle extra = data.getExtras();
			origin_picture = (Bitmap) extra.get("data");

			copyPicture();
			/* show taked picture */
			picture_view.setImageBitmap(origin_picture);

			recog_text.setText(String.valueOf(origin_picture.getWidth())
					+ String.valueOf(origin_picture.getHeight()));
			// character recognition in here

		}
	}

	@Override
	public void onClick(View view) {
		// TODO Auto-generated method stub
		if (view == translate_button) {
			doTranslate();
		} else if (view == capture_button) {
			doCapture();
		} else if (view == ocr_button) {
			// progcess dialog

			doOCR();
			// show result
		}
	}

	/*
	 * spinner language
	 */
	public void spinnerLanguage() {
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.from_lang, android.R.layout.simple_spinner_item);
		adapter
				.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
	}

	/*
	 * recognition
	 */
	public void doOCR() {
		// show progress dialog
		dialog = ProgressDialog.show(this, "Recognizing",
				"Please, wait for few minute......");

		// get language
		language = spinner.getSelectedItem().toString();
		// character recognition thread
		new Thread() {
			public void run() {

				File file = savePicture();
				Client client = new Client(file, language);
				if (client != null) {
					character = client.doOCR();
				} else {
					// show dialog cannot connect to server
				}

				// dismiss progress dialog
				Message message = new Message();
				message.what = RECOGNITION_OK;
				handler.sendMessage(message);

			}

		}.start();
	}

	// handler to dismiss progress dialog and show recognized result
	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			dialog.dismiss();
			switch (msg.what) {
			case RECOGNITION_OK:

				recog_text.setText(character);
				break;
			case RECOGNITION_ERROR:
				break;
			case CONNECTION_ERROR:
				break;
			default:
				break;
			}

		};
	};

	/*
	 * save picture
	 */

	public File savePicture() {
		String path = Environment.getExternalStorageDirectory().toString();
		File file = new File(path, "temp.jpg");
		try {
			FileOutputStream fout = new FileOutputStream(file);
			recog_picture.compress(Bitmap.CompressFormat.JPEG, 20, fout);
			fout.flush();
			fout.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return file;
	}

	/*
	 * take photo
	 */
	public void doCapture() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(intent, CAPTURE_PICTURE_CODE);
	}

	/*
	 * translate
	 */
	public void doTranslate() {
		Intent intent = new Intent(this, TranslateAc.class);
		intent.putExtra("character", character);
		startActivity(intent);
	}

	@Override
	public boolean onTouch(View view, MotionEvent event) {
		// TODO Auto-generated method stub
		if (view == picture_view) {
			int action = event.getAction();
			if (action == MotionEvent.ACTION_DOWN) {
				touchActionDown(event);
			} else if (action == MotionEvent.ACTION_MOVE) {
				touchActionMove(event);
			} else if (action == MotionEvent.ACTION_UP) {
				touchActionUp(event);
			}
		}
		if (view == layout) {
			undo();
		}
		return true;
	}

	/*
	 * undo
	 */
	private void undo() {
		picture_view.setImageBitmap(origin_picture);
		//
		copyPicture();
	}

	/*
	 * touch picture_view action up
	 */
	private void touchActionUp(MotionEvent event) {
		// TODO Auto-generated method stub
		end_x = event.getX();
		end_y = event.getY();
		// drawRect();
		cropPicture();
	}

	/*
	 * touch picture_view action move
	 */
	private void touchActionMove(MotionEvent event) {
		// TODO Auto-generated method stub
		end_x = event.getX();
		end_y = event.getY();
		drawRect();
	}

	/*
	 * touch picture_view action down
	 */
	private void touchActionDown(MotionEvent event) {
		// TODO Auto-generated method stub
		start_x = event.getX();
		start_y = event.getY();

	}

	/*
	 * draw rect
	 */
	private void drawRect() {

		Bitmap pic = Bitmap.createBitmap(recog_picture.getWidth(),
				recog_picture.getHeight(), Config.RGB_565);

		Canvas canvas = new Canvas(pic);
		Paint paint = new Paint();
		paint.setColor(Color.RED);
		paint.setStrokeWidth(4);
		// draw
		canvas.drawBitmap(recog_picture, 0, 0, paint);

		// scale
		scale(pic);
		// draw rect
		canvas.drawLine(scale_start_x, scale_start_y, scale_start_x,
				scale_end_y, paint);
		canvas.drawLine(scale_start_x, scale_start_y, scale_end_x,
				scale_start_y, paint);
		canvas.drawLine(scale_end_x, scale_end_y, scale_end_x, scale_start_y,
				paint);
		canvas.drawLine(scale_end_x, scale_end_y, scale_start_x, scale_end_y,
				paint);

		picture_view.setImageBitmap(pic);

		// preview(pic);
	}

	/*
	 * chuyen toa do tren view sang toa do thuc tren anh
	 */
	private void scale(Bitmap pic) {

		int pic_width = pic.getWidth();
		int pic_height = pic.getHeight();
		int view_width = picture_view.getWidth();
		int view_height = picture_view.getHeight();
		scale_start_x = (int) (pic_width * start_x / view_width);
		scale_start_y = (int) (pic_height * start_y / view_height);
		scale_end_x = (int) (pic_width * end_x / view_width);
		scale_end_y = (int) (pic_height * end_y / view_height);
	}

	/*
	 * crop picture
	 */
	private void cropPicture() {
		int pic_wid = recog_picture.getWidth();
		int pic_hig = recog_picture.getHeight();

		int wid = (int) Math.abs(scale_end_x - scale_start_x);
		int hig = (int) Math.abs(scale_end_y - scale_start_y);

		int st_x = scale_end_x < scale_start_x ? scale_end_x : scale_start_x;
		int st_y = scale_end_y < scale_start_y ? scale_end_y : scale_start_y;

		// check size
		if (st_x < 0)
			st_x = 0;
		if (st_y < 0)
			st_y = 0;
		if (st_x + wid > pic_wid) {
			wid = pic_wid - st_x;
		}
		if (st_y + hig > pic_hig) {
			hig = pic_hig - st_y;
		}

		// Log.i("size x",
		// String.valueOf(scale_end_x)+" "+String.valueOf(scale_start_x));
		// Log.i("size y",
		// String.valueOf(scale_end_y)+" "+String.valueOf(scale_start_y));
		// Log.i("size", String.valueOf(wid)+" "+String.valueOf(hig));
		if (wid > 0 && hig > 0) {
			recog_picture = Bitmap.createBitmap(recog_picture, (int) st_x,
					(int) st_y, wid, hig);
			picture_view.setImageBitmap(recog_picture);
		}
	}

	/*
	 * copy origin_picture save to recog_picture
	 */
	private void copyPicture() {
		recog_picture = Bitmap.createBitmap(origin_picture, 0, 0,
				origin_picture.getWidth(), origin_picture.getHeight());
	}

	/*
	 * show picture, change imageview size
	 */
	private void preview(Bitmap pic) {

		int view_width = picture_view.getWidth();
		int view_height = pic.getHeight() * view_width / pic.getWidth();

		LayoutParams params = picture_view.getLayoutParams();
		params.height = view_height;
		picture_view.setLayoutParams(params);
	}
}
